package com.zui.webapp.action;

import java.util.Calendar;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.ServletActionContext;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.hibernate.exception.ConstraintViolationException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.authentication.ProviderManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetails;

import com.zui.entity.party.HabooSupplier;
import com.zui.entity.party.PartyType;
import com.zui.entity.product.Image;
import com.zui.entity.product.Product;
import com.zui.entity.product.ProductImage;
import com.zui.entity.product.ProductType;
import com.zui.manager.ImageManager;
import com.zui.manager.ProductManager;
import com.zui.manager.SessionManager;
import com.zui.security.User;

@SuppressWarnings({"unchecked","rawtypes"})
public class HabooAction extends BaseJQGridAction {

	private static final long serialVersionUID = 1L;
	private static final Log log = LogFactory.getLog(HabooAction.class);
	
	private User user;
	private HabooSupplier supplier;
	private Product product;
	private Image image;
	public HabooAction() {}
	public HabooAction(SessionManager sessionManager) {
		this.sessionManager = sessionManager;
	}
	@Autowired
	private ProductManager productManager;
	@Autowired
	private ImageManager imageManager;
	@Autowired
	private SessionManager sessionManager;
	@Autowired
	@Qualifier("org.springframework.security.authenticationManager")
	private ProviderManager authenticationManager;

	/***********************************************************
	 * Business Method start
	 **********************************************************/
	public String signIn() {
		try {
			// Must be called from request filtered by Spring Security, otherwise SecurityContextHolder is not updated
		  UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(user.getUsername(), user.getPassword());
		  token.setDetails(new WebAuthenticationDetails(request));
		  Authentication authentication = authenticationManager.authenticate(token);
		  log.debug("Logging in with [{" + authentication.getPrincipal() + "}]");
		  SecurityContextHolder.getContext().setAuthentication(authentication);
		  jsonResult = "{\"result\":\"OK\"}";
		} catch (Exception e) {
		  SecurityContextHolder.getContext().setAuthentication(null);
		  log.error("Failure in autoLogin");
		  jsonResult = "{\"result\":\"Error\",\"reason\":\"Failure to sign your in, check your username and password and try again!\"}";
		}
		return "jsonResult";
	}
	public String saveSupplier() {
		if (supplier == null) {
			jsonResult = "{\"result\":\"Error\",\"reason\":\"No data was inputed.\"}";
			return "jsonResult";
		}
		try {
			if (supplier.getId() == null) {
				supplier.setPartyType(new PartyType(PartyType.HABOO_SUPPLIER));
				
				supplier.setCreatedByUserLogin(super.getCurrentUserName());
				supplier.setCreatedDate(Calendar.getInstance().getTime());
				supplier.setLastModifiedByUserLogin(super.getCurrentUserName());
				supplier.setLastModifiedDate(Calendar.getInstance().getTime());
				sessionManager.saveEntity(supplier);
				jsonResult = "{\"result\":\"OK\",\"supplier.id\"=\""+supplier.getId()+"\"}";
			} else {
				
				HabooSupplier s = (HabooSupplier)sessionManager.loadById(HabooSupplier.class, supplier.getId());
				s.setName(supplier.getName());
				s.setContact(supplier.getContact());
				s.setPNumber(supplier.getPNumber());
				s.setQq(supplier.getQq());
				s.setEmail(supplier.getEmail());
				s.setComments(supplier.getComments());
				sessionManager.saveOrUpdate(s);
				jsonResult = "{\"result\":\"OK\",\"supplier.id\"=\""+s.getId()+"\"}";
			}
		}catch (Exception e) {
			log.error(e.getMessage());
			jsonResult = "{\"result\":\"Error\",\"reason\":\"" + e.getMessage() + "\"}";
		}
		
		return "jsonResult";
	}
	public String saveProduct() {
		if (product == null) {
			jsonResult = "Error(No data inputed!)";
			return "jsonResult";
		}
		try {
			if (product.getId() == null) {
				product.setProductType(new ProductType(ProductType.TYPE_FINISHED_GOOD));
				
				product.setCreatedByUserLogin(super.getCurrentUserName());
				product.setCreatedDate(Calendar.getInstance().getTime());
				product.setLastModifiedByUserLogin(super.getCurrentUserName());
				product.setLastModifiedDate(Calendar.getInstance().getTime());
				sessionManager.saveEntity(product);
				jsonResult = "{\"result\":\"OK\",\"product.id\"=\""+product.getId()+"\"}";
			} else {
				
				Product p = (Product)sessionManager.loadById(Product.class, product.getId());
				p.setProductName(product.getProductName());
				p.setPrice(product.getPrice());
				p.setUnit(product.getUnit());
				p.setCbm(product.getCbm());
				p.setWeight(product.getWeight());
				p.setComments(product.getComments());
				p.setSupplier(product.getSupplier());
				
				p.setLastModifiedByUserLogin(super.getCurrentUserName());
				p.setLastModifiedDate(Calendar.getInstance().getTime());
				sessionManager.saveOrUpdate(p);
				jsonResult = "{\"result\":\"OK\",\"product.id\"=\""+p.getId()+"\"}";
			}
		} catch (ConstraintViolationException e) {
			log.error(e.getMessage());
			jsonResult = "{\"result\":\"Error\",\"reason\":\"Invalid supplier id.\"}";
		} catch (Exception e) {
			log.error(e.getMessage());
			jsonResult = "{\"result\":\"Error\",\"reason\":\"" + e.getMessage() + "\"}";
		}
		return "jsonResult";
	}
	public String savePhoto() {
		if (image == null) {
			jsonResult = "Error(No data inputed!)";
			return "jsonResult";
		}
		try {
	    	String relativePath = Image.DEFAULT_IMAGE_RELATIVE_PATH 
	    			+ System.getProperty("file.separator")
	    			+ "Haboo";
	    	String realPath = ServletActionContext.getServletContext().getRealPath("/") + relativePath;
	    	Image valueImage = image;
	    	image = new Image(uploadedFile, uploadedFileFileName, super.getAppContextPath(),relativePath, realPath);
	    	
	    	image.setOwnerCode(valueImage.getOwnerCode());
	    	image.setOwnerType(valueImage.getOwnerType());
	    	imageManager.addImage(image);
	    	
	    	if (image.getOwnerType()!=null && image.getOwnerType().equals("1")) {

	    		product = productManager.loadById(image.getOwnerCode());
	    		ProductImage pi = new ProductImage(image);
	    		product.addProductImage(pi);
	    		
				// update database
		    	productManager.saveOrUpdate(product);
		    	jsonResult = "{\"result\":\"OK\",\"image.id\"=\""+image.getId()+"\"}";
	    	}
	    	
		}catch (Exception e) {
			log.error(e.getMessage());
			jsonResult = "{\"result\":\"Error\",\"reason\":\"" + e.getMessage() + "\"}";
			return "jsonResult";
		}
    	
		
    	return "jsonResult";
	}
	public String deletePhoto() {
		if (image == null || image.getId() == null) {
			jsonResult = "Error(No data inputed!)";
			return "jsonResult";
		}
		try {

			image = imageManager.loadById(image.getId());
			if ("1".equals(image.getOwnerType())) {
				DetachedCriteria criteria = DetachedCriteria.forClass(ProductImage.class);
				criteria.add(Restrictions.eq("image.id", image.getId()));
				List<ProductImage> productImages = sessionManager.findByCriteria(criteria);
				if (productImages != null && !productImages.isEmpty())
					productManager.deleteProductImage(productImages.get(0));
				
				jsonResult = "{\"result\":\"OK\"}";
			} else {
				imageManager.deleteImage(image);
			}
		}catch (Exception e) {
			log.error(e.getMessage());
			jsonResult = "{\"result\":\"Error\",\"reason\":\"" + e.getMessage() + "\"}";
		}
    	
		
    	return "jsonResult";
	}
	/***********************************************************
	 * getters and setters
	 **********************************************************/
	public User getUser() {
		return user;
	}
	public HabooSupplier getSupplier() {
		return supplier;
	}
	public SessionManager getSessionManager() {
		return sessionManager;
	}
	public ProviderManager getAuthenticationManager() {
		return authenticationManager;
	}
	public void setUser(User user) {
		this.user = user;
	}
	public void setSupplier(HabooSupplier supplier) {
		this.supplier = supplier;
	}
	public void setSessionManager(SessionManager sessionManager) {
		this.sessionManager = sessionManager;
	}
	public void setAuthenticationManager(ProviderManager authenticationManager) {
		this.authenticationManager = authenticationManager;
	}
	public Product getProduct() {
		return product;
	}
	public Image getProductImage() {
		return image;
	}
	public ProductManager getProductManager() {
		return productManager;
	}
	public void setProduct(Product product) {
		this.product = product;
	}
	public void setProductImage(Image image) {
		this.image = image;
	}
	public void setProductManager(ProductManager productManager) {
		this.productManager = productManager;
	}
	public Image getImage() {
		return image;
	}
	public void setImage(Image image) {
		this.image = image;
	}
	
}
